package ch.ethz.fcl.metrobuzz.render.techniques.clip;

import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;

import ch.ethz.fcl.metrobuzz.spatialindex.object2d.Rectangle;

public class Clip {
	private static ByteBuffer byteBuffer = BufferUtils.createByteBuffer(256);
	private static DoubleBuffer doubleBuffer = byteBuffer.asDoubleBuffer();

	public static void clip(Rectangle bound) {
		clip(bound.getMinX(), bound.getMinY(), bound.getMaxX(), bound.getMaxY());
	}

	public static void clip(float minX, float minY, float maxX, float maxY) {
		GL11.glEnable(GL11.GL_CLIP_PLANE0);
		GL11.glEnable(GL11.GL_CLIP_PLANE1);
		GL11.glEnable(GL11.GL_CLIP_PLANE2);
		GL11.glEnable(GL11.GL_CLIP_PLANE3);
		doubleBuffer.clear();
		double[] top = { 0, -1, 0, maxY };
		doubleBuffer.put(top).rewind();
		GL11.glClipPlane(GL11.GL_CLIP_PLANE0, doubleBuffer);

		doubleBuffer.clear();
		double[] left = { 1, 0, 0, -minX };
		doubleBuffer.put(left).rewind();
		GL11.glClipPlane(GL11.GL_CLIP_PLANE1, doubleBuffer);

		doubleBuffer.clear();
		double[] right = { -1, 0, 0, maxX };
		doubleBuffer.put(right).rewind();
		GL11.glClipPlane(GL11.GL_CLIP_PLANE2, doubleBuffer);

		doubleBuffer.clear();
		double[] btm = { 0, 1, 0, -minY };
		doubleBuffer.put(btm).rewind();
		GL11.glClipPlane(GL11.GL_CLIP_PLANE3, doubleBuffer);
	}

	public static void disableClip() {
		GL11.glDisable(GL11.GL_CLIP_PLANE0);
		GL11.glDisable(GL11.GL_CLIP_PLANE1);
		GL11.glDisable(GL11.GL_CLIP_PLANE2);
		GL11.glDisable(GL11.GL_CLIP_PLANE3);
	}
}
